<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OACurrency;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class CurrencyLogic
 * @package App\Http\Controllers\Logic
 * @desc 币种增删改查
 */
class CurrencyLogic extends Controller
{
    //查询汇率
    public function getList($request)
    {
        $query = OACurrency::query();


            $query->when($request->filled('currency'),function($q) use ($request){
                return $q->where('currency','like',trim($request->currency).'%');
            });

        $count = $query->count('id');
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        $offset = ($page - 1) * $limit;
        $list = $query->offset($offset)->limit($limit)->get()->toArray();
        if(!$list) throw new \Exception($query->toSql());
        return ['list'=>$list,'total'=>$count];

    }

    //修改汇率
    public function editRate($input)
    {
//        手动事务
        DB::enableQueryLog();
        DB::beginTransaction();
        try{
            $currencyList = OACurrency::where('id',$input['id'])->first();
            if(OACurrency::query()->where('currency',$input['currency'])->where('id','<>',$input['id'])->exists()) throw new \Exception("币种" . $input['currency'].'已存在');
            $currencyList->currency = $input['currency'];
            $currencyList->rate = $input['rate'];
            $currencyList->save();
            DB::commit();
            return true;
        }catch(\Exception $e){
            DB::rollBack();
            throw new \Exception(DB::getQueryLog());
        }

    }

    public function addRate($request)
    {
        return OACurrency::query()->updateOrCreate(['currency'=>$request->currency],['currency'=>$request->currency,'rate'=>$request->rate]);
    }
}
